import ArticleItem from '@/components/ArticleItem'
import NavBar from '@/components/NavBar'
import { useAppSelector } from '@/store'
import { clearSearchResult, getSearchResult } from '@/store/action/search'
import { InfiniteScroll } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useLocation } from 'react-router'
import styles from './index.module.scss'

export default function SearchResult() {
  const { search } = useLocation()
  // MDN文档：https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams
  const searchParams = new URLSearchParams(search)
  // 获取 URL 的查询参数 q 的值
  const q = searchParams.get('q') || ''

  // console.log('获取查询参数q的值', q)
  const dispatch = useDispatch()
  // 🔔 交给无限加载组件发送请求，所以这里不需要了
  // useEffect(() => {
  //   dispatch(getSearchResult({ q: q }))
  // }, [q, dispatch])

  const { results } = useAppSelector((state) => state.search)

  // 是否还有更多内容
  const [hasMore, setHasMore] = useState(true)
  // 页码
  const page = useRef(0)
  // 加载更多的回调函数
  const loadMoreFn = async () => {
    // 页码加 1
    page.current = page.current + 1
    try {
      // 根据新的页码发送请求
      await dispatch(getSearchResult({ q: q, page: page.current, per_page: 10 }))
    } catch (error) {
      console.log(11111111111, error)
      // 没有分页数据需要更新状态，防止重复发送请求的死循环
      setHasMore(false)
    }
  }

  // 组件卸载时执行清理函数
  useEffect(() => {
    return () => {
      // 💥 组件卸载，清空搜索结果，修复新的搜索结果错误累加问题
      dispatch(clearSearchResult())
    }
  }, [dispatch])

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className='article-list'>
        {results.map((item) => (
          <ArticleItem key={item.art_id} article={item} />
        ))}
        {/* 
          InfiniteScroll 无限滚动组件 
            hasMore    是否还有更多内容
            loadMore   加载更多的回调函数
        */}
        <InfiniteScroll hasMore={hasMore} loadMore={loadMoreFn} />
      </div>
    </div>
  )
}
